package com.hdu.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hdu.dto.UserInfoDTO;
import com.hdu.entity.Class;
import com.hdu.entity.Student;
import com.hdu.mapper.StudentMapper;
import com.hdu.mapper.UserInfoMapper;
import com.hdu.pojo.PageBean;
import com.hdu.service.IStudentService;
import com.hdu.vo.StudentVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

/**
 * <p>
 * 学生实体类 服务实现类
 * </p>
 *
 * @author xiaobai
 * @since 2024-05-21
 */
@Service
@RequiredArgsConstructor
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements IStudentService {

    private final StudentMapper studentMapper;

    private final UserInfoMapper userInfoMapper;


    /**
     * 获取学生信息
     */
    @Override
    public PageBean<StudentVo> page(Integer page, Integer pageSize, String id, String username, String tID) {

        String cID = Db.lambdaQuery(Class.class).eq(Class::getTID, tID).one().getCID();

        //1. 设置分页参数
        PageHelper.startPage(page, pageSize);

        List<StudentVo> accountList = studentMapper.list(id, username, cID);

        Page<StudentVo> p = (Page<StudentVo>) accountList;

        //3. 封装PageBean对象
        return new PageBean<>(p.getTotal(), p.getResult());
    }

    /**
     * 获取学生详细信息
     */
    @Override
    public UserInfoDTO detail(String id) {
        UserInfoDTO userInfoDTO = userInfoMapper.getUserInfo(id);
        userInfoDTO.setSoleInfo(studentMapper.selectById(id));
        return userInfoDTO;
    }

    /**
     * 新增学生
     */
    @Override
    public void append(String id, String tID) {
        String cID = Db.lambdaQuery(Class.class).eq(Class::getTID, tID).one().getCID();
        UpdateWrapper<Student> wrapper = new UpdateWrapper<>();
        wrapper.set("cID", cID).eq("sID", id);
        studentMapper.update(null, wrapper);
    }

    /**
     * 编辑学生
     */
    @Override
    public void update(StudentVo account) {
        Student student = new Student();
        student.setId(String.valueOf(account.getId()));
        student.setTime(LocalDate.parse(account.getCreateTime()));
        studentMapper.updateById(student);
        // 更新用户信息
        userInfoMapper.updateAvatar(account.getId(),account.getAvatar());
    }

    /**
     * 删除学生
     */
    @Override
    public void delete(List<String> idList) {
        studentMapper.delete(idList);
    }
}
